//请求用  
var proto_field_request = {};
//请求用
var dict_request = {};
//请求用
var parselist_request = {};
//编辑用
var editmodel = [];
//表格用
var tablelist = [];
//存储bits修改表当前选中行
var bits_modify_id = 0;
//bits修改表用
var bits_modify_tablelist = [];
//穿越用
var dictfeild = [];
//穿越用
var parselistfeild = [];

var protofeild = [];

var dictObj = []

var parselistObj = []

//比特位表ID
var currentId_bits = 0
var cacheObj = {}
var id_cache = []
//比特位修改表ID
var modify_currentId_bits = 0
var modify_cacheObj = {}
var modify_id_cache = []


$.ajax({
	url: 'http://' + ipm + ':8081/dict/query',
	type: 'POST',
	contentType: 'application/json',
	dataType: 'json',
	data: {},
	success: function (response) {
		console.log(response);
		protofieldRead(response);
		createProtofieldobj(response);
		getDictName(response);
		getParselistName(response);
		// console.log(dictfeild);
		// console.log(parselistfeild);
		// console.log(tablelist);
		console.log(tablelist)

		for (var i = 0; i < dictfeild.length; i++) {
			var d_obj = {}
			d_obj.value = dictfeild[i].name;
			d_obj.text = dictfeild[i].name;
			dictObj.push(d_obj);
		}
		//console.log(dictObj);

		for (var i = 0; i < parselistfeild.length; i++) {
			var p_obj = {}
			p_obj.value = parselistfeild[i].name;
			p_obj.text = parselistfeild[i].name;
			parselistObj.push(p_obj);
		}
		for (var i = 0; i < 10; i++) {
			if (dictfeild && parselistfeild && protofeild && dictObj && parselistObj) {
				createTab();
			} else {
				alert('加载失败，请刷新重试')
			}
		}
	}
});

function refreshTab() {
	$.ajax({
		url: 'http://' + ipm + ':8081/dict/query',
		type: 'POST',
		contentType: 'application/json',
		dataType: 'json',
		data: {},
		success: function (response) {
			console.log(response);
			tablelist = [];
			protofieldRead(response);
		}
	});
}

function getDictName(args) {
	var dm8data = args.data;
	var dm8content = dm8data.content;
	var datalist = [];
	var testa;
	var testb;
	var i = 0;
	var j = 0;
	var k = 1;
	for (i; i < dm8content.length; i++) {
		if (dm8content[i].cfgType == 1) {
			datalist[i] = dm8content[i].content;
			testa = JSON.parse(datalist[i]);
			dict_request = testa;
			console.log(testa);
			testb = testa.dict;
			for (j; j < testb.length; j++) {
				var tableA = {
					"name": "",
					"inserttime": "",
					"updatetime": "",
					"ID": ""
				};
				editmodel.push(testb[j].context);
				tableA.name = testb[j].name;
				tableA.inserttime = dm8content[i].inserttime;
				tableA.updatetime = dm8content[i].updatetime;
				tableA.ID = k++;
				dictfeild.push(tableA);
			}
		}
	}
}

function getParselistName(args) {
	var dm8data = args.data;
	var dm8content = dm8data.content;
	var datalist = [];
	var testa;
	var testb;
	var i = 0;
	var j = 0;
	var k = 1;
	for (i; i < dm8content.length; i++) {
		if (dm8content[i].cfgType == 2) {
			datalist[i] = dm8content[i].content;
			testa = JSON.parse(datalist[i]);
			parselist_request = testa;
			testb = testa.parse_list;
			for (j; j < testb.length; j++) {
				var tableA = {
					"name": "",
					"inserttime": "",
					"updatetime": "",
					"ID": ""
				};
				editmodel.push(testb[j].context);
				tableA.name = testb[j].name;
				tableA.inserttime = dm8content[i].inserttime;
				tableA.updatetime = dm8content[i].updatetime;
				tableA.ID = k++;
				parselistfeild.push(tableA);
			}
		}
	}
}


function createTab() {
	$("#table_page").bootstrapTable('destroy').bootstrapTable({
		data: tablelist,
		// data: [{
		// 	"id": "1",
		// 	"name": "abc",
		// 	"value_type": "int",
		// 	"value_length": "4",
		// 	"method": "字典",
		// 	"value": "test",
		// 	"unit": "m",
		// 	"ID": "1"
		// }, {
		// 	"id": "2",
		// 	"name": "abc",
		// 	"value_type": "int",
		// 	"value_length": "4",
		// 	"method": "位处理",
		// 	"value": "bits",
		// 	"unit": "m",
		// 	"ID": "2"
		// }],
		dataType: 'json',
		striped: true,                      //是否显示行间隔色
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		pagination: true,                   //是否显示分页（*）
		sortable: true,                     //是否启用排序
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 10,                     //每页的记录行数（*）
		pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
		search: false,                      //是否显示表格搜索
		strictSearch: true,
		minimumCountColumns: 1,             //最少允许的列数
		clickToSelect: true,                //是否启用点击选中行
		uniqueId: "id",                     //每一行的唯一标识，一般为主键列
		cardView: false,                    //是否显示详细视图
		detailView: false,                  //是否显示父子表
		//得到查询的参数
		onEditableSave: onEditableSave,
		queryParams: function (params) {
			//这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
			var temp = {
				rows: params.limit,                         //页面大小
				page: (params.offset / params.limit) + 1,   //页码
				sort: params.sort,      //排序列名  
				sortOrder: params.order //排位命令（desc，asc） 
			};
			return temp;
		},

		columns: [{
			field: 'ID',
			title: 'ID'
		}, {
			field: 'name',
			title: '名称',
			editable: editable_cn
		}, {
			field: 'value_type',
			title: '值类型',
			editable: {
				type: 'select',
				title: '值类型',
				source: [{
					value: "char",
					text: "char"
				}, {
					value: "short",
					text: "short"
				}, {
					value: "int",
					text: "int"
				}, {
					value: "double",
					text: "double"
				}, {
					value: "float",
					text: "float"
				}, {
					value: "long",
					text: "long"
				}, {
					value: "unsigned char",
					text: "unsigned char"
				}, {
					value: "unsigned short",
					text: "unsigned short"
				}, {
					value: "unsigned int",
					text: "unsigned int"
				}, {
					value: "unsigned long",
					text: "unsigned long"
				}]
			}
		}, {
			field: 'value_length',
			title: '值长度',
			editable: lengthLimit
		}, {
			field: 'method',
			title: '处理方法',
			editable: {
				type: 'select',
				title: '值类型',
				source: [{
					value: "字典",
					text: "字典"
				}, {
					value: "逻辑表达式",
					text: "逻辑表达式"
				}, {
					value: "解析表",
					text: "解析表"
				}, {
					value: "字符串",
					text: "字符串"
				}, {
					value: "原始值",
					text: "原始值"
				}, {
					value: "分隔符",
					text: "分隔符"
				}, {
					value: "位处理",
					text: "位处理"
				}
				]
			}
		}, {
			field: 'value',
			title: '方法',
			editable: valueChangeObj,
		}, {
			field: 'unit',
			title: '单位',
			editable: editable_cn
		}, {
			field: 'dbfield',
			title: '数据库表字段名称',
			editable: editable_cn
		}, {
			field: 'id',
			title: '操作',
			width: 120,
			align: 'center',
			valign: 'middle',
			formatter: actionFormatter
		},
		]
	});
}

//编辑保存
function onEditableSave(field, row, rowIndex, oldValue, $el) {
	// alert("字段名：" + field + "，当前值：" + row[field] + "，旧值：" + oldValue + "，顺位：" + rowIndex);
	var data = $("#table_page").bootstrapTable('getData');
	var objChange = data[rowIndex];
	var idChange = objChange.id;
	var arr = proto_field_request.protocol_segments;
	var protosegmentsWeb = {
		"cfgType": "3",
		"cfgName": "proto_segment_cfg.json",
		"content": "",
	}
	var protosegmentsSave = {
		"cfg_type": 3,
		"segment_max_id": "",
		"protocol_segments": ""
	}
	if (field == "name") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].name = row[field];
			}
		}
		protosegmentsSave.protocol_segments = arr;
		protosegmentsSave.segment_max_id = proto_field_request.segment_max_id;
		protosegmentsWeb.content = JSON.stringify(protosegmentsSave)
		postQuestSave(protosegmentsWeb);
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "value_type") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].value_type = row[field];
				if (row[field] == "char") {
					arr[i].value_length = 1;
				} else if (row[field] == "short") {
					arr[i].value_length = 2;
				} else if (row[field] == "int") {
					arr[i].value_length = 4;
				} else if (row[field] == "double") {
					arr[i].value_length = 8;
				} else if (row[field] == "float") {
					arr[i].value_length = 4;
				} else if (row[field] == "long") {
					arr[i].value_length = 8;
				} else if (row[field] == "unsigned char") {
					arr[i].value_length = 1;
				} else if (row[field] == "unsigned short") {
					arr[i].value_length = 2;
				} else if (row[field] == "unsigned int") {
					arr[i].value_length = 4;
				} else if (row[field] == "unsigned long") {
					arr[i].value_length = 8;
				}
			}
		}
		protosegmentsSave.protocol_segments = arr;
		protosegmentsSave.segment_max_id = proto_field_request.segment_max_id;
		protosegmentsWeb.content = JSON.stringify(protosegmentsSave)
		postQuestSave(protosegmentsWeb);
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "value_length") {
		for (var i = 0; i < arr.length; i++) {
			if (objChange.value_type != "char" && objChange.value_type != "unsigned char") {
				alert("非char类型无法修改");
				return
			} else if (arr[i].id == idChange) {
				arr[i].value_length = parseInt(row[field]);
			}
		}
		protosegmentsSave.protocol_segments = arr;
		protosegmentsSave.segment_max_id = proto_field_request.segment_max_id;
		protosegmentsWeb.content = JSON.stringify(protosegmentsSave)
		postQuestSave(protosegmentsWeb);
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "value") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				if (objChange.method == "字典") {
					arr[i].dict_name = row[field];
				} else if (objChange.method == "逻辑表达式") {
					arr[i].logical_expressions = row[field];
				} else if (objChange.method == "解析表") {
					arr[i].parse_list_name = row[field];
				} else if (objChange.method == "原始值") {
					//layer.msg('原始值方式无法修改', { icon: 2 });
					alert("原始值方式无法修改");
					window.location.reload();
					return false;
				} else if (objChange.method == "字符串") {
					alert("字符串方式无法修改");
					window.location.reload();
					return false;
				} else if (objChange.method == "分隔符") {
					arr[i].strtrim = row[field];
				}
			}
		}
		protosegmentsSave.protocol_segments = arr;
		protosegmentsSave.segment_max_id = proto_field_request.segment_max_id;
		protosegmentsWeb.content = JSON.stringify(protosegmentsSave)
		postQuestSave(protosegmentsWeb);
		window.location.reload();
		alert("修改成功");
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "method") {
		// console.log(oldValue);
		// console.log(objChange);
		// console.log(idChange);
		// console.log(arr);
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				if (oldValue == "字典") {
					delete arr[i].dict_name
					methodChange(row[field], arr[i]);
				} else if (oldValue == "逻辑表达式") {
					delete arr[i].logical_expressions
					methodChange(row[field], arr[i]);
				} else if (oldValue == "解析表") {
					delete arr[i].parse_list_name
					methodChange(row[field], arr[i]);
				} else if (oldValue == "原始值") {
					delete arr[i].string
					methodChange(row[field], arr[i]);
				} else if (oldValue == "字符串") {
					delete arr[i].string
					methodChange(row[field], arr[i]);
				} else if (oldValue == "分隔符") {
					delete arr[i].strtrim
					methodChange(row[field], arr[i]);
				} else if (oldValue == "位处理") {
					delete arr[i].bits
					methodChange(row[field], arr[i]);
				}
			}
		}
		protosegmentsSave.protocol_segments = arr;
		protosegmentsSave.segment_max_id = proto_field_request.segment_max_id;
		protosegmentsWeb.content = JSON.stringify(protosegmentsSave)
		postQuestSave(protosegmentsWeb);
		window.location.reload();
		alert("修改成功");
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "unit") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].unit = row[field];
			}
		}
		protosegmentsSave.protocol_segments = arr;
		protosegmentsSave.segment_max_id = proto_field_request.segment_max_id;
		protosegmentsWeb.content = JSON.stringify(protosegmentsSave)
		postQuestSave(protosegmentsWeb);
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "dbfield") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dbfield = row[field];
			}
		}
		protosegmentsSave.protocol_segments = arr;
		protosegmentsSave.segment_max_id = proto_field_request.segment_max_id;
		protosegmentsWeb.content = JSON.stringify(protosegmentsSave)
		postQuestSave(protosegmentsWeb);
		layer.msg('修改成功', { icon: 1 });
	}
	// protosegmentsSave.protocol_segments = arr;
	// protosegmentsSave.segment_max_id = proto_field_request.segment_max_id;
	// protosegmentsWeb.content = JSON.stringify(proto_field_request)
	// postQuestSave(protosegmentsWeb);
	// layer.msg('修改成功', { icon: 1 });
}

//编辑处理方法变更类
function methodChange(args, arr) {
	if (args == "字典") {
		arr.dict_name = "null";
	} else if (args == "逻辑表达式") {
		arr.logical_expressions = "null";
	} else if (args == "解析表") {
		arr.parse_list_name = "null";
	} else if (args == "原始值") {
		arr.string = "hex";
	} else if (args == "字符串") {
		arr.string = "ascii";
	} else if (args == "分隔符") {
		arr.strtrim = "null";
	} else if (args == "位处理") {
		arr.bits = [{ "mask": "0 ~ 0", "name": "", "string": "hex", "unit": "" }];
	}
	return arr;
}

// function valueFormatter(value, row, index) {

// 	if (value == "bits") {
// 		console.log(value)
// 		console.log(row)
// 		console.log(index)
// 	}
// 	return false

// }

function actionFormatter(value, row, index) {
	var id = value;
	//var name = row[index].name;
	//console.log(name);
	var result = "";
	result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"protosegment_modify(" + id + ")\" title='删除'><span class='feather-trash-2'></span></a>";

	return result;
}

//长度输入限制
function lengthLimit(rowIndex) {
	// console.log(rowIndex)
	var data = $("#table_page").bootstrapTable('getData');
	// console.log(data[rowIndex].value_type)

	if (data[rowIndex].value_type == "char") {
		return {
			type: 'number',
		}
	} else if (data[rowIndex].value_type == "short") {
		return {
			disabled: true
		}
	} else if (data[rowIndex].value_type == "int") {
		return {
			disabled: true
		}
	} else if (data[rowIndex].value_type == "double") {
		return {
			disabled: true
		}
	} else if (data[rowIndex].value_type == "float") {
		return {
			disabled: true
		}
	} else if (data[rowIndex].value_type == "long") {
		return {
			disabled: true
		}
	} else if (data[rowIndex].value_type == "unsigned char") {
		return {
			type: 'number',
		}
	} else if (data[rowIndex].value_type == "unsigned short") {
		return {
			disabled: true
		}
	} else if (data[rowIndex].value_type == "unsigned int") {
		return {
			disabled: true
		}
	} else if (data[rowIndex].value_type == "unsigned long") {
		return {
			disabled: true
		}
	}
}


function valueChangeObj(rowIndex) {
	var data = $("#table_page").bootstrapTable('getData');
	if (data[rowIndex].method == "字典") {
		return {
			type: 'select',
			title: '值类型',
			source: dictObj
		}
	} else if (data[rowIndex].method == "逻辑表达式") {
		return true;
	} else if (data[rowIndex].method == "解析表") {
		return {
			type: 'select',
			title: '值类型',
			source: parselistObj
		};
	} else if (data[rowIndex].method == "原始值") {
		return {
			disabled: true
		};
	} else if (data[rowIndex].method == "字符串") {
		return {
			disabled: true
		};
	} else if (data[rowIndex].method == "分隔符") {
		return true;
	}
	else if (data[rowIndex].method == "位处理") {
		return {
			disabled: true,
			noEditFormatter: function (value, row, index) {
				var result = "";
				// result += "<a href='javascript:;' class='btn btn-xs blue' onclick=\"editBitsModel_modify('" + index + "')\" title='编辑'><span class='feather-edit'></span></a>";
				result += "<a href='javascript:;' class='btn btn-xs blue' onclick=\"editBitsModel_modify('" + index + "')\" title='编辑'><span class='feather-edit'></span></a>";
				return result;
			}
		}
	}
}


//删除协议字段解析表JSON
function protosegment_modify(id) {
	var arrProtosegment = []
	var protosegmentsWeb = {
		"cfgType": "3",
		"cfgName": "proto_segment_cfg.json",
		"content": "",
		// "syncNodes": ""
	}
	protosegmentsWeb.id = parseInt(id);
	arrProtosegment.push(protosegmentsWeb)
	sss = JSON.stringify(arrProtosegment)
	console.log(protosegmentsWeb)
	console.log(arrProtosegment)
	console.log(sss)
	$.ajax({
		url: 'http://' + ipm + ':8081/dict/deleteProto',
		type: 'POST',
		contentType: 'application/json',
		dataType: 'json',
		data: sss,
		success: function (response) {
			console.log(response);
		}
	});
	window.location.reload();
}


//新增协议字段模态框
function createProtofieldModel() {
	$('#protofieldModal').modal('show');
}


//比特位编辑模态框-新增
function editBitsModel() {
	$('#bitsModal').modal('show');
}

//比特位编辑模态框-新增
function hideBitsModel() {
	$('#bitsModal').modal('hide');
}



//比特位编辑模态框-修改
function editBitsModel_modify(rowIndex) {
	console.log(rowIndex)
	bits_modify_id = rowIndex
	arrBits = proto_field_request.protocol_segments[rowIndex].bits
	bits_modify_tablelist = []
	var k = 0
	for (var i = 0; i < arrBits.length; i++) {
		var bits_modify_tablelist_part = {
			bit_mask_start: "",
			bit_mask_end: "",
			bit_name: "",
			bit_method: "",
			bit_value: "",
			bit_unit: "",
			bit_dbfield: "",
			ID: "",
		}
		mask_index = arrBits[i].mask.indexOf("~")
		bits_modify_tablelist_part.bit_mask_start = arrBits[i].mask.substring(0, mask_index - 1)
		bits_modify_tablelist_part.bit_mask_end = arrBits[i].mask.substring(mask_index + 1)
		bits_modify_tablelist_part.bit_name = arrBits[i].name
		if (arrBits[i].dict_name == "") {
			bits_modify_tablelist_part.bit_method = "字典";
			bits_modify_tablelist_part.bit_value = "未定义"
		} else if (arrBits[i].dict_name) {
			bits_modify_tablelist_part.bit_method = "字典";
			bits_modify_tablelist_part.bit_value = arrBits[i].dict_name;
		}
		else if (arrBits[i].logical_expressions == "") {
			bits_modify_tablelist_part.bit_method = "逻辑表达式";
			bits_modify_tablelist_part.bit_value = "未定义";
		}
		else if (arrBits[i].logical_expressions) {
			bits_modify_tablelist_part.bit_method = "逻辑表达式";
			bits_modify_tablelist_part.bit_value = arrBits[i].logical_expressions;
		}
		else if (arrBits[i].parse_list_name == "") {
			bits_modify_tablelist_part.bit_method = "解析表";
			bits_modify_tablelist_part.bit_value = "未定义";
		}
		else if (arrBits[i].parse_list_name) {
			bits_modify_tablelist_part.bit_method = "解析表";
			bits_modify_tablelist_part.bit_value = arrBits[i].parse_list_name;
		}
		else if (arrBits[i].string == "hex") {
			bits_modify_tablelist_part.bit_method = "原始值";
			bits_modify_tablelist_part.bit_value = arrBits[i].string;
		}
		else if (arrBits[i].string == "ascii") {
			bits_modify_tablelist_part.bit_method = "字符串";
			bits_modify_tablelist_part.bit_value = arrBits[i].string;
		}
		else if (arrBits[i].strtrim == "") {
			bits_modify_tablelist_part.bit_method = "分隔符";
			bits_modify_tablelist_part.bit_value = "未定义";
		}
		else if (arrBits[i].strtrim) {
			bits_modify_tablelist_part.bit_method = "分隔符";
			bits_modify_tablelist_part.bit_value = arrBits[i].strtrim;
		}
		bits_modify_tablelist_part.bit_unit = arrBits[i].unit
		bits_modify_tablelist_part.bit_dbfield = arrBits[i].dbfield
		bits_modify_tablelist_part.ID = k
		bits_modify_tablelist.push(bits_modify_tablelist_part)
		k++;
	}


	modify_currentId_bits = bits_modify_tablelist[bits_modify_tablelist.length - 1].ID + 1
	// console.log(modify_currentId_bits)
	//比特位编辑表-修改表
	$("#bitsEditTable").bootstrapTable('destroy').bootstrapTable({
		data: bits_modify_tablelist,
		dataType: 'json',
		striped: true,                      //是否显示行间隔色
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		pagination: false,                   //是否显示分页（*）
		sortable: false,                     //是否启用排序
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 5,                     //每页的记录行数（*）
		search: false,                      //是否显示表格搜索
		strictSearch: true,
		showColumns: false,                  //是否显示所有的列（选择显示的列）
		showRefresh: false,                  //是否显示刷新按钮
		showExport: false,
		minimumCountColumns: 1,             //最少允许的列数
		clickToSelect: false,                //是否启用点击选中行
		uniqueId: 'ID',
		columns: [{
			field: 'bit_mask_start',
			align: 'center',
			title: '起始位',
			width: 80,
			formatter: function (value, row, index) {
				return '<div><input type="number" min="0" class="form-control" name="bit_mask_start' + index + '" id="bit_mask_start' + index + '" value = ' + value + '></div>';
			}
		}, {
			field: 'bit_mask_end',
			align: 'center',
			title: '结束位',
			width: 80,
			formatter: function (value, row, index) {
				return '<div><input type="number" min="0" class="form-control" name="bit_mask_end' + index + '" id="bit_mask_end' + index + '"  value = ' + value + '></div></div>';
			}
		}, {
			field: 'bit_name',
			align: 'center',
			title: '名称',
			width: 160,
			formatter: function (value, row, index) {
				return '<div><input type="text" class="form-control" name="bit_name' + index + '" id="bit_name' + index + '"  value = ' + value + '></div>';
			}
		}, {
			field: 'bit_method',
			align: 'center',
			title: '解决方式',
			width: 140,
			formatter: function (value, row, index) {
				// if (value == "dict_name") {
				// 	return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name" selected>字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex" >原始值</option><option value="strtrim">分隔符</option></select>';
				// } else if (value == "logical_expressions") {
				// 	return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions" selected>逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex">原始值</option><option value="strtrim">分隔符</option></select>';
				// } else if (value == "parse_list_name") {
				// 	return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name" selected>解析表</option><option value="ascii">字符串</option><option value="hex">原始值</option><option value="strtrim">分隔符</option></select>';
				// } else if (value == "ascii") {
				// 	return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii" selected>字符串</option><option value="hex">原始值</option><option value="strtrim">分隔符</option></select>';
				// } else if (value == "hex") {
				// 	return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex" selected>原始值</option><option value="strtrim">分隔符</option></select>';
				// } else if (value == "strtrim") {
				// 	return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex">原始值</option><option value="strtrim" selected>分隔符</option></select>';
				// } else {
				// 	return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex">原始值</option><option value="strtrim">分隔符</option></select>';
				// }
				if (value == "字典") {
					return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name" selected>字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex" >原始值</option><option value="strtrim">分隔符</option></select>';
				} else if (value == "逻辑表达式") {
					return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions" selected>逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex">原始值</option><option value="strtrim">分隔符</option></select>';
				} else if (value == "解析表") {
					return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name" selected>解析表</option><option value="ascii">字符串</option><option value="hex">原始值</option><option value="strtrim">分隔符</option></select>';
				} else if (value == "字符串") {
					return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii" selected>字符串</option><option value="hex">原始值</option><option value="strtrim">分隔符</option></select>';
				} else if (value == "原始值") {
					return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex" selected>原始值</option><option value="strtrim">分隔符</option></select>';
				} else if (value == "分隔符") {
					return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex">原始值</option><option value="strtrim" selected>分隔符</option></select>';
				} else {
					return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '"   class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex">原始值</option><option value="strtrim">分隔符</option></select>';
				}
			}
		}, {
			field: 'bit_value',
			align: 'center',
			width: 160,
			title: '方法',
			formatter: function (value, row, index) {
				console.log(value)
				// console.log(row.bit_method)
				if (row.bit_method == "字典") {
					var oProtofeild = "";
					for (var i = 0; i < dictfeild.length; i++) {
						if (dictfeild[i].name == value) {
							oProtofeild += '<option value=' + dictfeild[i].name + ' selected>' + dictfeild[i].name + '</option>'
						} else {
							oProtofeild += '<option value=' + dictfeild[i].name + '>' + dictfeild[i].name + '</option>'
						}
					}
					return '<div id="bit_input_model' + index + '" style="display: none;"><input type="text" class="form-control" name="bit_value_input' + index + '" id="bit_value_input' + index + '"  ></div><div id="bit_select_model' + index + '" ><select  name="bit_value_select' + index + '" id="bit_value_select' + index + '"   class="form-control" ><option value=""></option>' + oProtofeild + '</div>';
				} else if (row.bit_method == "解析表") {
					var oProtofeild = "";
					for (var i = 0; i < parselistfeild.length; i++) {
						if (parselistfeild[i].name == value) {
							oProtofeild += '<option value=' + parselistfeild[i].name + ' selected>' + parselistfeild[i].name + '</option>'
						} else {
							oProtofeild += '<option value=' + parselistfeild[i].name + '>' + parselistfeild[i].name + '</option>'

						}
					}
					return '<div id="bit_input_model' + index + '" style="display: none;"><input type="text" class="form-control" name="bit_value_input' + index + '" id="bit_value_input' + index + '"  ></div><div id="bit_select_model' + index + '" ><select  name="bit_value_select' + index + '" id="bit_value_select' + index + '"   class="form-control" ><option value=""></option>' + oProtofeild + '</div>';
				} else {
					return '<div id="bit_input_model' + index + '" ><input type="text" class="form-control" name="bit_value_input' + index + '" id="bit_value_input' + index + '"  value = ' + value + ' ></div><div id="bit_select_model' + index + '" style="display: none;"><select  name="bit_value_select' + index + '" id="bit_value_select' + index + '"  class="form-control" ><option value=""></option></div>';
				}
			}
		}, {
			field: 'bit_unit',
			align: 'center',
			title: '单位',
			width: 80,
			formatter: function (value, row, index) {
				return '<div><input type="text" class="form-control" name="bit_unit' + index + '" id="bit_unit' + index + '"  value = ' + value + ' ></div>';
			}
		}, {
			field: 'bit_dbfield',
			align: 'center',
			title: '数据库表字段名称',
			width: 160,
			formatter: function (value, row, index) {
				return '<div><input type="text" class="form-control" name="bit_dbfield' + index + '" id="bit_dbfield' + index + '"  value = ' + value + ' ></div>';
			}
		}, {
			field: 'ID',
			align: 'center',
			title: '删除',
			formatter: function (value, row, index) {
				console.log(value)
				return "<a href='javascript:;' class='btn btn-xs red' onclick=\"deleteRow('" + value + "','" + index + "', 'bitsEditTable')\" title='删除'><span class='feather-trash-2'></span></a>";
			}
		}
		]
	});
	$('#bitsEditModal').modal('show');
}

layui.config({
	base: 'step-lay/'
}).use(['form', 'step'], function () {
	var $ = layui.$
		, form = layui.form
		, step = layui.step;

	step.render({
		elem: '#stepForm',
		filter: 'stepForm',
		width: '100%', //设置容器宽度
		stepWidth: '750px',
		height: '600px',
		stepItems: [{
			title: '第一步'
		}, {
			title: '第二步'
		}, {
			title: '完成'
		}]
	});


	form.on('submit(formStep)', function (data) {
		step.next('#stepForm');
		return false;
	});

	form.on('submit(formStep2)', function (data) {
		step.next('#stepForm');
		return false;
	});

	$('.pre').click(function () {
		step.pre('#stepForm');
	});

	$('.next').click(function () {
		step.next('#stepForm');
	});
})

var field
layui.use('form', function () {
	var form = layui.form;

	$('#confirm').on('click', function (data) {
		form.submit('protofield', function (data) { // 注：v2.7.0 新增
			// 回调函数返回结果跟上述 submit 事件完全一致
			field = data.field;
			if (field.method == "parse_list_name") {
				field.length = "解析表"
				field.value_type = "解析表"
			}
			console.log(data.field)
			var confirmTextA = "名称 : " + field.name;
			var confirmTextB = "值类型 : " + field.value_type;
			if (field.length) {
				field.length = field.length;
			}
			else if (field.value_type == "char") {
				field.length = 1;
			} else if (field.value_type == "short") {
				field.length = 2;
			} else if (field.value_type == "int") {
				field.length = 4;
			} else if (field.value_type == "double") {
				field.length = 8;
			} else if (field.value_type == "float") {
				field.length = 4;
			} else if (field.value_type == "long") {
				field.length = 8;
			} else if (field.value_type == "unsigned char") {
				field.length = 1;
			} else if (field.value_type == "unsigned short") {
				field.length = 2;
			} else if (field.value_type == "unsigned int") {
				field.length = 4;
			} else if (field.value_type == "unsigned long") {
				field.length = 8;
			}
			var confirmTextC = "值长度 : " + field.length;
			var method_cn
			if (field.method == "dict_name") {
				method_cn = "字典"
			} else if (field.method == "logical_expressions") {
				method_cn = "逻辑表达式"
			} else if (field.method == "parse_list_name") {
				method_cn = "解析表"
			} else if (field.method == "ascii") {
				method_cn = "字符串"
			} else if (field.method == "hex") {
				method_cn = "原始值"
			} else if (field.method == "strtrim") {
				method_cn = "分隔符"
			} else if (field.method == "bits") {
				method_cn = "位处理"
			}
			var confirmTextD = "解决方式 : " + method_cn;
			// var confirmTextD = "解决方式 : " + field.method;
			var confirmTextE = "解决方法 : " + field.methodvalue;
			var confirmTextF = "单位 : " + field.unit;
			var confirmTextG = "数据库表名称 : " + field.dbfield;
			$("#textA").text(confirmTextA);
			$("#textB").text(confirmTextB);
			$("#textC").text(confirmTextC);
			$("#textD").text(confirmTextD);
			$("#textE").text(confirmTextE);
			$("#textF").text(confirmTextF);
			$("#textG").text(confirmTextG);
		});
	});

	//方法提交
	$('#testSubmitBtn').on('click', function (data) {
		form.submit('protofield', function (data) { // 注：v2.7.0 新增
			// 回调函数返回结果跟上述 submit 事件完全一致
			field = data.field;
			//console.log(data.field)
			// do something
			protosegmentsJson();
		});
		return false;
	});


	//隐藏长度框
	form.on('select(value_type)', function (data) {
		console.log(data.value);
		if (data.value == "char") {
			$('#length').val("");
			$('#value_length').show();
		} else if (data.value == "short") {
			$('#length').val("");
			$('#value_length').hide();
		} else if (data.value == "int") {
			$('#length').val("");
			$('#value_length').hide();
		} else if (data.value == "double") {
			$('#length').val("");
			$('#value_length').hide();
		} else if (data.value == "float") {
			$('#length').val("");
			$('#value_length').hide();
		} else if (data.value == "long") {
			$('#length').val("");
			$('#value_length').hide();
		} else if (data.value == "unsigned char") {
			$('#length').val("");
			$('#value_length').show();
		} else if (data.value == "unsigned short") {
			$('#length').val("");
			$('#value_length').hide();
		} else if (data.value == "unsigned int") {
			$('#length').val("");
			$('#value_length').hide();
		} else if (data.value == "unsigned long") {
			$('#length').val("");
			$('#value_length').hide();
		}
		form.render('select');
	});
	//解决方式选择触发隐藏事件
	form.on('select(method)', function (data) {
		console.log(data.value);
		if (data.value == "dict_name") {
			//置空方法选择框
			$('#methodvalueS').empty();
			//隐藏方法输入框并且置空
			$('#inputType').hide();
			$('#methodvalue').val("");
			//显示方法选择框
			$('#selectType').show();
			//显示类型和长度框
			$('#value_type').show();
			$('#value_length').show();
			//隐藏单位框
			$('#value_unit').hide();
			$('#unit').val("");
			//隐藏比特位编辑
			$('#value_bits').hide();
			console.log(dictfeild);
			var oProtofeild = "";
			for (var i = 0; i < dictfeild.length; i++) {
				oProtofeild += '<option value=' + dictfeild[i].name + '>' + dictfeild[i].name + '</option>'
			}
			$("#methodvalueS").append(oProtofeild);
		} else if (data.value == "parse_list_name") {
			//置空方法选择框
			$('#methodvalueS').empty();
			//显示方法选择框
			$('#selectType').show();
			//隐藏方法输入框并且置空
			$('#inputType').hide();
			$('#methodvalue').val("");
			//隐藏类型和长度框
			$('#value_type').hide();
			$('#value_length').hide();
			//隐藏单位框
			$('#value_unit').hide();
			$('#unit').val("");
			//隐藏比特位编辑
			$('#value_bits').hide();
			console.log(parselistfeild);
			var oProtofeild = "";
			for (var i = 0; i < parselistfeild.length; i++) {
				oProtofeild += '<option value=' + parselistfeild[i].name + '>' + parselistfeild[i].name + '</option>'
			}
			$("#methodvalueS").append(oProtofeild);
		} else if (data.value == "logical_expressions") {
			//置空方法选择框
			$('#methodvalueS').empty();
			//隐藏方法选择框
			$('#selectType').hide();
			//显示方法输入框并且置空
			$('#methodvalue').val("");
			$('#inputType').show();
			//显示类型和长度框
			$('#value_type').show();
			$('#value_length').show();
			//显示单位框
			$('#value_unit').show();
			$('#unit').val("");
			//隐藏比特位编辑
			$('#value_bits').hide();
		} else if (data.value == "ascii") {
			//置空方法选择框
			$('#methodvalueS').empty();
			//隐藏方法选择框
			$('#selectType').hide();
			//隐藏方法输入框并且置空
			$('#methodvalue').val("");
			$('#inputType').hide();
			//显示类型和长度框
			$('#value_type').show();
			$('#value_length').show();
			//显示单位框
			$('#value_unit').show();
			$('#unit').val("");
			//隐藏比特位编辑
			$('#value_bits').hide();
		} else if (data.value == "hex") {
			//置空方法选择框
			$('#methodvalueS').empty();
			//隐藏方法选择框
			$('#selectType').hide();
			//隐藏方法输入框并且置空
			$('#methodvalue').val("");
			$('#inputType').hide();
			//显示类型和长度框
			$('#value_type').show();
			$('#value_length').show();
			//显示单位框
			$('#value_unit').show();
			$('#unit').val("");
			//隐藏比特位编辑
			$('#value_bits').hide();
		} else if (data.value == "strtrim") {
			//置空方法选择框
			$('#methodvalueS').empty();
			//隐藏方法选择框
			$('#selectType').hide();
			//显示方法输入框并且置空
			$('#methodvalue').val("");
			$('#inputType').show();
			//显示类型和长度框
			$('#value_type').show();
			$('#value_length').show();
			//显示单位框
			$('#value_unit').show();
			$('#unit').val("");
			//隐藏比特位编辑
			$('#value_bits').hide();
		} else if (data.value == "bits") {
			//置空方法选择框
			$('#methodvalueS').empty();
			//隐藏方法选择框
			$('#selectType').hide();
			//隐藏方法输入框并且置空
			$('#methodvalue').val("");
			$('#inputType').hide();
			//隐藏类型和长度框
			$('#value_type').show();
			$('#value_length').show();
			//隐藏单位框
			$('#value_unit').hide();
			$('#unit').val("");
			//显示比特位编辑
			$('#value_bits').show();
		} else if (data.value == "null") {
			//置空方法选择框
			$('#methodvalueS').empty();
			//隐藏方法选择框
			$('#selectType').hide();
			//隐藏方法输入框并且置空
			$('#methodvalue').val("");
			$('#inputType').hide();
			//隐藏类型和长度框
			$('#value_type').hide();
			$('#value_length').hide();
			//隐藏单位框
			$('#value_unit').hide();
			$('#unit').val("");
			//隐藏比特位编辑
			$('#value_bits').hide();
		}
		form.render('select');
	});
});


//创建一个协议字段JSON
function protosegmentsJson() {
	var arr = proto_field_request.protocol_segments;
	var id = proto_field_request.segment_max_id;
	id++;
	var protosegmentsWeb = {
		"cfgType": "3",
		"cfgName": "proto_segment_cfg.json",
		"content": "",
		// "syncNodes": ""
	}
	var protosegmentsSave = {
		"cfg_type": 3,
		"segment_max_id": "",
		"protocol_segments": ""
	}
	if (id) {
		var protosegments = {
			"id": "",
			"name": "",
			"dbfield": "", // 2024-01-10
			"value_type": "",
			"value_length": "",
			"x-x-x": "",
			"unit": "无"
		}
		protosegments.id = id;
	} else {
		arr = []
		var protosegments = {
			"id": "",
			"name": "",
			"dbfield": "", // 2024-01-10
			"value_type": "",
			"value_length": "",
			"x-x-x": "",
			"unit": "无"
		}
		id = 0;
		protosegments.id = 0;
	}
	console.log(protosegments)
	protosegments.name = field.name;
	protosegments.dbfield = field.dbfield;
	protosegments.value_type = field.value_type;
	if (protosegments.value_type == "char") {
		protosegments.value_length = 1;
	} else if (protosegments.value_type == "short") {
		protosegments.value_length = 2;
	} else if (protosegments.value_type == "int") {
		protosegments.value_length = 4;
	} else if (protosegments.value_type == "double") {
		protosegments.value_length = 8;
	} else if (protosegments.value_type == "float") {
		protosegments.value_length = 4;
	} else if (protosegments.value_type == "long") {
		protosegments.value_length = 8;
	} else if (protosegments.value_type == "unsigned char") {
		protosegments.value_length = 1;
	} else if (protosegments.value_type == "unsigned short") {
		protosegments.value_length = 2;
	} else if (protosegments.value_type == "unsigned int") {
		protosegments.value_length = 4;
	} else if (protosegments.value_type == "unsigned long") {
		protosegments.value_length = 8;
	}
	if (field.length) {
		protosegments.value_length = parseInt(field.length);
	}
	//protosegments.x-x-x = parseInt(field.methodvalue);
	if (field.method == "ascii") {
		protosegments = JSON.parse(JSON.stringify(protosegments).replace('x-x-x', 'string'))
	} else if (field.method == "hex") {
		protosegments = JSON.parse(JSON.stringify(protosegments).replace('x-x-x', 'string'))
	} else {
		protosegments = JSON.parse(JSON.stringify(protosegments).replace('x-x-x', field.method))
	}
	if (field.method == "dict_name") {
		protosegments.dict_name = field.methodvalueS;
	} else if (field.method == "logical_expressions") {
		protosegments.logical_expressions = field.methodvalue;
	} else if (field.method == "parse_list_name") {
		protosegments.parse_list_name = field.methodvalueS;
		//待添加，对应解析表的类型与长度
	} else if (field.method == "ascii") {
		protosegments.string = field.method;
	} else if (field.method == "hex") {
		protosegments.string = field.method;
	} else if (field.method == "strtrim") {
		protosegments.strtrim = field.methodvalue;
	} else if (field.method == "bits") {

		// console.log($("#bitsTable").find("tr").length)
		// $('#bitsTable tr').each(function (i) {
		// 	$('#bit_select_model' + (i - 1)).show();
		// });

		var data = $("#form-add").serializeArray();
		// alert(JSON.stringify(data))
		var Bits = []
		for (var i = 0; i < data.length; i++) {
			Bits_part = {
				"mask": "",
				"name": "",
				"x-x-x": "x-x-x",
				"unit": ""
			}
			var obj = {}
			data[i].name = "mask_start";
			data[i + 1].name = "mask_end";
			data[i + 2].name = "name";
			data[i + 3].name = "bit_method";
			data[i + 4].name = "bit_input_value";
			data[i + 5].name = "bit_select_value";
			data[i + 6].name = "unit";
			data[i + 6].name = "dbfield";
			obj[data[i].name] = data[i]['value'];
			obj[data[i + 1].name] = data[i + 1]['value'];
			obj[data[i + 2].name] = data[i + 2]['value'];
			obj[data[i + 3].name] = data[i + 3]['value'];
			obj[data[i + 4].name] = data[i + 4]['value'];
			obj[data[i + 5].name] = data[i + 5]['value'];
			obj[data[i + 6].name] = data[i + 6]['value'];
			Bits_part.mask = obj.mask_start + " ~ " + obj.mask_end
			Bits_part.name = obj.name
			if (obj.bit_method == "dict_name") {
				Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'dict_name'))
				Bits_part.dict_name = obj.bit_select_value
			} else if (obj.bit_method == "logical_expressions") {
				Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'logical_expressions'))
				Bits_part.logical_expressions = obj.bit_input_value
			} else if (obj.bit_method == "parse_list_name") {
				Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'parse_list_name'))
				Bits_part.parse_list_name = obj.bit_select_value
			} else if (obj.bit_method == "ascii") {
				Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'string'))
				Bits_part.string = "ascii"
			} else if (obj.bit_method == "hex") {
				Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'string'))
				Bits_part.string = "hex"
			} else if (obj.bit_method == "strtrim") {
				Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'strtrim'))
				Bits_part.parse_list_name = obj.bit_input_value
			}
			Bits_part.unit = obj.unit
			Bits_part.dbfield = obj.dbfield
			Bits.push(Bits_part);
			i = i + 7;
		}
		console.log(Bits)
		protosegments.bits = Bits;
	}
	protosegments.unit = field.unit;
	console.log(protosegments);
	arr.push(protosegments);
	//console.log(arr);
	protosegmentsSave.protocol_segments = arr;
	protosegmentsSave.segment_max_id = id;
	protosegmentsWeb.content = JSON.stringify(protosegmentsSave);
	postQuestSave(protosegmentsWeb);
	alert("新增成功！");
	window.location.reload();

}

//比特位编辑表
$(function () {
	$("#bitsTable").bootstrapTable({
		dataType: 'json',
		striped: true,                      //是否显示行间隔色
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		pagination: false,                   //是否显示分页（*）
		sortable: false,                     //是否启用排序
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 10,                     //每页的记录行数（*）
		pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
		search: false,                      //是否显示表格搜索
		strictSearch: true,
		showColumns: false,                  //是否显示所有的列（选择显示的列）
		showRefresh: false,                  //是否显示刷新按钮
		showExport: false,
		Icons: 'glyphicon-export icon-share',
		minimumCountColumns: 1,             //最少允许的列数
		clickToSelect: false,                //是否启用点击选中行
		uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
		cardView: false,                    //是否显示详细视图
		detailView: false,                  //是否显示父子表
		columns: [{
			field: 'mask',
			align: 'center',
			title: '起始位',
			width: 80,
			formatter: function (value, row, index) {
				return '<div><input type="number" min="0" class="form-control" name="bit_mask_start' + index + '" id="bit_mask_start' + index + '" /></div>';
			}
		}, {
			field: 'mask',
			align: 'center',
			title: '结束位',
			width: 80,
			formatter: function (value, row, index) {
				return '<div><input type="number" min="0" class="form-control" name="bit_mask_end' + index + '" id="bit_mask_end' + index + '" /></div></div>';
			}
		}, {
			field: 'name',
			align: 'center',
			title: '名称',
			width: 160,
			formatter: function (value, row, index) {
				return '<div><input type="text" class="form-control" name="bit_name' + index + '" id="bit_name' + index + '" /></div>';
			}
		}, {
			field: 'type_method',
			align: 'center',
			title: '解决方式',
			width: 140,
			formatter: function (value, row, index) {
				return '<select onchange="selectChange(this,' + index + ')" name="bit_method' + index + '" id="bit_method' + index + '" class="form-control"><option value="null">请选择</option><option value="dict_name">字典</option><option value="logical_expressions">逻辑表达式</option><option value="parse_list_name">解析表</option><option value="ascii">字符串</option><option value="hex">原始值</option><option value="strtrim">分隔符</option></select>';
			}
		}, {
			field: 'type_value',
			align: 'center',
			title: '方法',
			width: 160,
			formatter: function (value, row, index) {
				return '<div id="bit_input_model' + index + '" style="display: none;"><input type="text" class="form-control" name="bit_value_input' + index + '" id="bit_value_input' + index + '" /></div><div id="bit_select_model' + index + '" style="display: none;"><select  name="bit_value_select' + index + '" id="bit_value_select' + index + '"  class="form-control" ><option value=""></option></div>';
			}
		}, {
			field: 'unit',
			align: 'center',
			title: '单位',
			width: 80,
			formatter: function (value, row, index) {
				return '<div><input type="text" class="form-control" name="bit_unit' + index + '" id="bit_unit' + index + '" /></div>';
			}
		}, {
			field: 'dbfield',
			align: 'center',
			title: '数据库表字段名称',
			width: 160,
			formatter: function (value, row, index) {
				return '<div><input type="text" class="form-control" name="bit_dbfield' + index + '" id="bit_dbfield' + index + '" /></div>';
			}
		}, {
			field: 'ID',
			align: 'center',
			title: '删除',
			formatter: function (value, row, index) {
				return "<a href='javascript:;' class='btn btn-xs red' onclick=\"deleteRow('" + value + "','" + index + "', 'bitsTable')\" title='删除'><span class='feather-trash-2'></span></a>";
			}
		}
		]
	});
});

//联动选择字典选项更新
function dict_select_update() {

}
//联动选择解析表选项更新
function parselist_select_update() {

}

//bit表选择更换触发事件
function selectChange(that, index) {
	if (that.value == "dict_name") {
		$('#bit_input_model' + index).hide();
		$('#bit_select_model' + index).show();
		$('#bit_value_select' + index).empty();
		console.log(dictfeild);
		var oProtofeild = "";
		for (var i = 0; i < dictfeild.length; i++) {
			oProtofeild += '<option value=' + dictfeild[i].name + '>' + dictfeild[i].name + '</option>'
		}
		$('#bit_value_select' + index).append(oProtofeild);
	} else if (that.value == "parse_list_name") {
		$('#bit_input_model' + index).hide();
		$('#bit_select_model' + index).show();
		$('#bit_value_select' + index).empty();
		console.log(parselistfeild);
		var oProtofeild = "";
		for (var i = 0; i < parselistfeild.length; i++) {
			oProtofeild += '<option value=' + parselistfeild[i].name + '>' + parselistfeild[i].name + '</option>'
		}
		$('#bit_value_select' + index).append(oProtofeild);
	} else if (that.value == "ascii") {
		$('#bit_input_model' + index).show();
		$('#bit_select_model' + index).hide();
		$('#bit_value_select' + index).empty();
		var oProtofeild = "<option value=''></option>";
		$('#bit_value_select' + index).append(oProtofeild);
		$('#bit_value_input' + index).val("ascii");
	} else if (that.value == "hex") {
		$('#bit_input_model' + index).show();
		$('#bit_select_model' + index).hide();
		$('#bit_value_select' + index).empty();
		var oProtofeild = "<option value=''></option>";
		$('#bit_value_select' + index).append(oProtofeild);
		$('#bit_value_input' + index).val("hex");
	} else {
		$('#bit_input_model' + index).show();
		$('#bit_select_model' + index).hide();
		$('#bit_value_select' + index).empty();
		var oProtofeild = "<option value=''></option>";
		$('#bit_value_select' + index).append(oProtofeild);
		$('#bit_value_input' + index).val("");
	}
	console.log(that.value);
}



//比特位表新增
function addBit(tableName) {
	id_cache = []
	modify_id_cache = []
	mask_start_cache = []
	mask_end_cache = []
	name_cache = []
	type_method_cache = []
	type_value_cache = []
	unit_cache = []
	dbfield_cache = []
	//获取值
	$('#' + tableName + ' tr').each(function (i) {
		mask_start_cache.push($(this).find('td:eq(0) input').val())
		mask_end_cache.push($(this).find('td:eq(1) input').val())
		name_cache.push($(this).find('td:eq(2) input').val())
		type_method_cache.push($(this).find('td:eq(3) select').val())//获取第i行select框数据
		if ($(this).find('td:eq(3) select').val() == "dict_name" || $(this).find('td:eq(3) select').val() == "parse_list_name") {
			type_value_cache.push($(this).find('td:eq(4) select').val())
		} else {
			type_value_cache.push($(this).find('td:eq(4) input').val())
		}
		unit_cache.push($(this).find('td:eq(5) input').val())
		dbfield_cache.push($(this).find('td:eq(6) input').val())
	});

	if (tableName == "bitsTable") {
		for (var i = 0; i < currentId_bits + 1; i++) {
			id_cache.push(i)
		}
		var row = {
			ID: currentId_bits,
		}
		currentId_bits++
	} else if (tableName == "bitsEditTable") {
		for (var i = 0; i < modify_currentId_bits + 1; i++) {
			modify_id_cache.push(i)
		}
		var row = {
			ID: modify_currentId_bits,
		}
		modify_currentId_bits++
	}
	// var row = {
	// 	ID: currentId_bits,
	// 	mask_start: "",
	// 	mask_end: "",
	// 	name: "",
	// 	type_method: "",
	// 	type_input_value: "",
	// 	type_select_value: "",
	// 	unit: "",
	// }
	$('#' + tableName + '').bootstrapTable('append', row);
	$('#' + tableName + ' tr').each(function (i) {
		$(this).find('td:eq(0) input').val(mask_start_cache[i])
		$(this).find('td:eq(1) input').val(mask_end_cache[i])
		$(this).find('td:eq(2) input').val(name_cache[i])
		$(this).find('td:eq(3) select').val(type_method_cache[i])
		if (type_method_cache[i] == "dict_name") {
			$('#bit_select_model' + (i - 1)).show();
			$('#bit_input_model' + (i - 1)).hide();
			var oProtofeild = "";
			for (var j = 0; j < dictfeild.length; j++) {
				oProtofeild += '<option value=' + dictfeild[j].name + '>' + dictfeild[j].name + '</option>'
			}
			$('#bit_value_select' + (i - 1)).append(oProtofeild);
			$(this).find('td:eq(4) select').val(type_value_cache[i])
		} else if (type_method_cache[i] == "parse_list_name") {
			$('#bit_select_model' + (i - 1)).show();
			$('#bit_input_model' + (i - 1)).hide();
			var oProtofeild = "";
			for (var j = 0; j < parselistfeild.length; j++) {
				oProtofeild += '<option value=' + parselistfeild[j].name + '>' + parselistfeild[j].name + '</option>'
			}
			$('#bit_value_select' + (i - 1)).append(oProtofeild);
			$(this).find('td:eq(4) select').val(type_value_cache[i])
		} else {
			$('#bit_select_model' + (i - 1)).hide();
			$('#bit_input_model' + (i - 1)).show();
			$(this).find('td:eq(4) input').val(type_value_cache[i])
		}
		$(this).find('td:eq(5) input').val(unit_cache[i])
		$(this).find('td:eq(6) input').val(dbfield_cache[i])
	}
	);


}
//比特位表删除
function deleteRow(args_id, args_index, tableName) {
	mask_start_cache = []
	mask_end_cache = []
	name_cache = []
	type_method_cache = []
	type_value_cache = []
	unit_cache = []
	dbfield_cache = []
	//获取值
	$('#' + tableName + ' tr').each(function (i) {
		mask_start_cache.push($(this).find('td:eq(0) input').val())
		mask_end_cache.push($(this).find('td:eq(1) input').val())
		name_cache.push($(this).find('td:eq(2) input').val())
		type_method_cache.push($(this).find('td:eq(3) select').val())//获取第i行select框数据
		if ($(this).find('td:eq(3) select').val() == "dict_name" || $(this).find('td:eq(3) select').val() == "parse_list_name") {
			type_value_cache.push($(this).find('td:eq(4) select').val())
		} else {
			type_value_cache.push($(this).find('td:eq(4) input').val())
		}
		unit_cache.push($(this).find('td:eq(5) input').val())
		dbfield_cache.push($(this).find('td:eq(6) input').val())
	});
	$('#' + tableName + '').bootstrapTable('removeByUniqueId', args_id)
	args_index++
	mask_start_cache.splice(args_index, 1)
	mask_end_cache.splice(args_index, 1)
	name_cache.splice(args_index, 1)
	type_method_cache.splice(args_index, 1)
	type_value_cache.splice(args_index, 1)
	unit_cache.splice(args_index, 1)
	dbfield_cache.splice(args_index, 1)
	$('#' + tableName + ' tr').each(function (i) {
		$(this).find('td:eq(0) input').val(mask_start_cache[i])
		$(this).find('td:eq(1) input').val(mask_end_cache[i])
		$(this).find('td:eq(2) input').val(name_cache[i])
		$(this).find('td:eq(3) select').val(type_method_cache[i])
		if (type_method_cache[i] == "dict_name") {
			$('#bit_select_model' + (i - 1)).show();
			$('#bit_input_model' + (i - 1)).hide();
			var oProtofeild = "";
			for (var j = 0; j < dictfeild.length; j++) {
				oProtofeild += '<option value=' + dictfeild[j].name + '>' + dictfeild[j].name + '</option>'
			}
			$('#bit_value_select' + (i - 1)).append(oProtofeild);
			$(this).find('td:eq(4) select').val(type_value_cache[i])
		} else if (type_method_cache[i] == "parse_list_name") {
			$('#bit_select_model' + (i - 1)).show();
			$('#bit_input_model' + (i - 1)).hide();
			var oProtofeild = "";
			for (var j = 0; j < parselistfeild.length; j++) {
				oProtofeild += '<option value=' + parselistfeild[j].name + '>' + parselistfeild[j].name + '</option>'
			}
			$('#bit_value_select' + (i - 1)).append(oProtofeild);
			$(this).find('td:eq(4) select').val(type_value_cache[i])
		} else {
			$('#bit_select_model' + (i - 1)).hide();
			$('#bit_input_model' + (i - 1)).show();
			$(this).find('td:eq(4) input').val(type_value_cache[i])
		}
		$(this).find('td:eq(5) input').val(unit_cache[i])
		$(this).find('td:eq(6) input').val(dbfield_cache[i])
	}
	);
}

//拼接比特json
function submitBits() {
	var data = $("#form-add").serializeArray();
	alert(JSON.stringify(data))
	var Bits = []
	for (var i = 0; i < data.length; i++) {
		Bits_part = {
			"mask": "",
			"name": "",
			"x-x-x": "x-x-x",
			"unit": "",
			"dbfield": ""
		}
		var obj = {}
		data[i].name = "mask_start";
		data[i + 1].name = "mask_end";
		data[i + 2].name = "name";
		data[i + 3].name = "bit_method";
		data[i + 4].name = "bit_input_value";
		data[i + 5].name = "bit_select_value";
		data[i + 6].name = "unit";
		data[i + 7].name = "dbfield";
		obj[data[i].name] = data[i]['value'];
		obj[data[i + 1].name] = data[i + 1]['value'];
		obj[data[i + 2].name] = data[i + 2]['value'];
		obj[data[i + 3].name] = data[i + 3]['value'];
		obj[data[i + 4].name] = data[i + 4]['value'];
		obj[data[i + 5].name] = data[i + 5]['value'];
		obj[data[i + 6].name] = data[i + 6]['value'];
		obj[data[i + 7].name] = data[i + 7]['value'];
		Bits_part.mask = obj.mask_start + " ~ " + obj.mask_end
		Bits_part.name = obj.name
		if (obj.bit_method == "dict_name") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'dict_name'))
			Bits_part.dict_name = obj.bit_select_value
		} else if (obj.bit_method == "logical_expressions") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'logical_expressions'))
			Bits_part.logical_expressions = obj.bit_input_value
		} else if (obj.bit_method == "parse_list_name") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'parse_list_name'))
			Bits_part.parse_list_name = obj.bit_select_value
		} else if (obj.bit_method == "ascii") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'string'))
			Bits_part.string = "ascii"
		} else if (obj.bit_method == "hex") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'string'))
			Bits_part.string = "hex"
		} else if (obj.bit_method == "strtrim") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'strtrim'))
			Bits_part.parse_list_name = obj.bit_input_value
		}
		Bits_part.unit = obj.unit
		Bits_part.dbfield = obj.dbfield
		Bits.push(Bits_part);
		i = i + 7;

	}
	///123
	console.log(Bits)
}


//编辑比特json并保存
function saveEditBit() {
	var data = $("#form-edit").serializeArray();
	// alert(JSON.stringify(data))
	var Bits = []
	for (var i = 0; i < data.length; i++) {
		Bits_part = {
			"mask": "",
			"name": "",
			"x-x-x": "x-x-x",
			"unit": "",
			"dbfield": ""
		}
		var obj = {}
		data[i].name = "mask_start";
		data[i + 1].name = "mask_end";
		data[i + 2].name = "name";
		data[i + 3].name = "bit_method";
		data[i + 4].name = "bit_input_value";
		data[i + 5].name = "bit_select_value";
		data[i + 6].name = "unit";
		data[i + 7].name = "dbfield";
		obj[data[i].name] = data[i]['value'];
		obj[data[i + 1].name] = data[i + 1]['value'];
		obj[data[i + 2].name] = data[i + 2]['value'];
		obj[data[i + 3].name] = data[i + 3]['value'];
		obj[data[i + 4].name] = data[i + 4]['value'];
		obj[data[i + 5].name] = data[i + 5]['value'];
		obj[data[i + 6].name] = data[i + 6]['value'];
		obj[data[i + 7].name] = data[i + 7]['value'];
		Bits_part.mask = obj.mask_start + " ~ " + obj.mask_end
		Bits_part.name = obj.name
		if (obj.bit_method == "dict_name") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'dict_name'))
			Bits_part.dict_name = obj.bit_select_value
		} else if (obj.bit_method == "logical_expressions") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'logical_expressions'))
			Bits_part.logical_expressions = obj.bit_input_value
		} else if (obj.bit_method == "parse_list_name") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'parse_list_name'))
			Bits_part.parse_list_name = obj.bit_select_value
		} else if (obj.bit_method == "ascii") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'string'))
			Bits_part.string = "ascii"
		} else if (obj.bit_method == "hex") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'string'))
			Bits_part.string = "hex"
		} else if (obj.bit_method == "strtrim") {
			Bits_part = JSON.parse(JSON.stringify(Bits_part).replace('x-x-x', 'strtrim'))
			Bits_part.parse_list_name = obj.bit_input_value
		}
		Bits_part.unit = obj.unit
		Bits_part.dbfield = obj.dbfield
		Bits.push(Bits_part);
		i = i + 7;

	}
	///123
	console.log(proto_field_request)

	console.log(Bits)

	var arr = proto_field_request.protocol_segments;
	var protosegmentsWeb = {
		"cfgType": "3",
		"cfgName": "proto_segment_cfg.json",
		"content": "",
	}
	var protosegmentsSave = {
		"cfg_type": 3,
		"segment_max_id": "",
		"protocol_segments": ""
	}
	arr[bits_modify_id].bits = Bits
	protosegmentsSave.protocol_segments = arr;
	protosegmentsSave.segment_max_id = proto_field_request.segment_max_id;
	protosegmentsWeb.content = JSON.stringify(proto_field_request)
	console.log(protosegmentsWeb)

	// postQuestSave(protosegmentsWeb);
	var xhr = new XMLHttpRequest();
	// 配置请求
	xhr.open('POST', 'http://' + ipm + ':8081/dict/save', true);
	xhr.setRequestHeader('content-Type', 'application/json');
	// 发送 JSON 数据
	xhr.send(JSON.stringify(protosegmentsWeb));
	// 监听请求的状态
	xhr.onreadystatechange = function () {
		console.log(xhr.readyState);
		if (xhr.readyState === 4 && xhr.status === 200) {
			console.log(xhr.responseText);
			$.ajax({
				url: 'http://' + ipm + ':8081/dict/query',
				type: 'POST',
				contentType: 'application/json',
				dataType: 'json',
				data: {},
				success: function (response) {
					tablelist=[]
					console.log(response);
					protofieldRead(response);
					createTab();
				}
			});
		}
	};
	alert("修改成功");
	// window.location.reload();
}

